import traceback
import re

from rest_framework import status, viewsets, permissions, serializers
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.shortcuts import get_object_or_404
from django.conf import settings
from user.models import SysUser
from django.utils import timezone
from django.db.models import Q
from datetime import datetime, timedelta
import logging

from .models import Meeting, MeetingTranscript, MeetingSummary, OptimizedTranscript
from .serializers import (
    MeetingSerializer, MeetingTranscriptSerializer,
    MeetingSummarySerializer, CreateMeetingSerializer
)
from .speech_service import get_speech_recognition_service
from .coze_service import get_coze_service

logger = logging.getLogger(__name__)


class MeetingViewSet(viewsets.ModelViewSet):
    """会议视图集"""
    serializer_class = MeetingSerializer
    permission_classes = [IsAuthenticated]
    lookup_field = 'meeting_id'  # 使用meeting_id作为查找字段

    def get_queryset(self):
        """只返回用户作为主持人的会议"""
        user = self.request.user
        return Meeting.objects.filter(host=user).order_by('-created_at')

    def get_object(self):
        """获取会议对象，支持meeting_id查找"""
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
        filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}

        try:
            obj = Meeting.objects.get(**filter_kwargs)
            # 检查用户是否有权限访问此会议
            user = self.request.user
            if obj.host != user:
                from rest_framework.exceptions import PermissionDenied
                raise PermissionDenied('您没有权限访问此会议')
            return obj
        except Meeting.DoesNotExist:
            from rest_framework.exceptions import NotFound
            raise NotFound('会议不存在')

    def perform_create(self, serializer):
        """创建会议时自动设置主持人"""
        serializer.save(host=self.request.user)

    def destroy(self, request, *args, **kwargs):
        """删除会议"""
        instance = self.get_object()
        meeting_id = instance.meeting_id
        title = instance.title

        # 检查用户是否有权限删除此会议
        if instance.host != request.user:
            return Response({
                'success': False,
                'error': '您没有权限删除此会议'
            }, status=status.HTTP_403_FORBIDDEN)

        # 执行删除操作
        self.perform_destroy(instance)

        return Response({
            'success': True,
            'message': f'会议"{title}"(ID: {meeting_id})已成功删除'
        })

    @action(detail=False, methods=['post'])
    def create_meeting(self, request):
        """创建会议的专用接口"""
        try:
            logger.info(f"开始创建会议，用户: {request.user.username}")
            logger.info(f"请求数据: {request.data}")

            serializer = CreateMeetingSerializer(data=request.data)
            if serializer.is_valid():
                logger.info("序列化器验证通过，开始保存会议")
                meeting = serializer.save(host=request.user)
                logger.info(f"会议创建成功，ID: {meeting.id}, meeting_id: {meeting.meeting_id}")

                response_serializer = MeetingSerializer(meeting)
                return Response({
                    'success': True,
                    'meeting': response_serializer.data,
                    'message': '会议创建成功'
                })
            else:
                logger.error(f"序列化器验证失败: {serializer.errors}")
                return Response({
                    'success': False,
                    'error': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            logger.error(f"创建会议失败: {str(e)}")
            logger.error(f"错误详情: {traceback.format_exc()}")
            return Response({
                'success': False,
                'error': f'创建会议失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    # 在 views.py 文件中的 start_meeting 方法中添加冲突检查
    @action(detail=True, methods=['post'])
    def start_meeting(self, request, meeting_id=None):
        """开始会议（仅主持人）"""
        meeting = self.get_object()

        if meeting.host != request.user:
            return Response({
                'success': False,
                'error': '只有主持人可以开始会议'
            }, status=status.HTTP_403_FORBIDDEN)

        # 检查是否在允许的时间范围内开始
        now = timezone.now()
        time_diff = (meeting.scheduled_time - now).total_seconds()

        # 如果会议已经开始超过5分钟，则不允许开始
        if time_diff < -300:  # -300秒 = -5分钟
            return Response({
                'success': False,
                'error': '会议已过开始时间5分钟以上，无法开始会议'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 如果会议开始时间还未到5分钟内，则提示用户
        if time_diff > 300:  # 300秒 = 5分钟
            scheduled_time_str = meeting.scheduled_time.strftime("%Y-%m-%d %H:%M")
            return Response({
                'success': False,
                'error': f'会议只能在计划开始时间（{scheduled_time_str}）前5分钟内开始，现在还不能开始会议。'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 检查是否有正在进行的快速会议
        active_meetings = Meeting.objects.filter(
            host=request.user,
            status='active'
        ).exclude(meeting_id=meeting.meeting_id)

        if active_meetings.exists():
            return Response({
                'success': False,
                'error': '您已有会议正在进行，请先结束当前会议'
            }, status=status.HTTP_400_BAD_REQUEST)

        meeting.status = 'active'
        meeting.actual_start_time = timezone.now()
        meeting.save()

        return Response({
            'success': True,
            'message': '会议已开始',
            'meeting': MeetingSerializer(meeting).data
        })

    @action(detail=False, methods=['post'])
    def quick_start_meeting(self, request):
        """快速开始会议"""
        try:
            logger.info(f"开始快速创建会议，用户: {request.user.username}")

            # 默认会议参数
            title = request.data.get('title', f"{request.user.username}的会议")
            duration = request.data.get('duration', 60)  # 默认60分钟

            # 使用当前时间作为开始时间
            scheduled_time = timezone.now()
            scheduled_end_time = scheduled_time + timedelta(minutes=duration)

            # 检查时间冲突 - 检查未来5分钟内是否有计划中的会议
            conflict_check_time = scheduled_time + timedelta(minutes=5)
            conflicting_meetings = Meeting.objects.filter(
                scheduled_time__lt=scheduled_end_time,
                scheduled_end_time__gt=conflict_check_time,
                status__in=['scheduled', 'active']  # 只检查计划中和进行中的会议
            ).exclude(status='ended').exclude(status='cancelled').exclude(
                status__in=['scheduled', 'active'],
                actual_end_time__isnull=False  # 排除状态为scheduled/active但实际已结束的会议
            )

            if conflicting_meetings.exists():
                conflict_meeting = conflicting_meetings.first()
                # 检查是否在预约会议开始前5分钟内
                if conflict_meeting.status == 'scheduled' and conflict_meeting.scheduled_time <= scheduled_end_time:
                    time_diff = (conflict_meeting.scheduled_time - scheduled_time).total_seconds()
                    if 0 <= time_diff <= 300:  # 5分钟内
                        conflict_time = conflict_meeting.scheduled_time.strftime("%Y-%m-%d %H:%M")
                        raise serializers.ValidationError({
                            '计划时间': f'未来5分钟内有预约会议 "{conflict_meeting.title}" ({conflict_time}) 即将开始，无法创建快速会议。'
                        })

            meeting_data = {
                'title': title,
                'description': request.data.get('description', ''),
                'scheduled_time': scheduled_time,
                'duration': duration,
                'enable_transcription': True,
                'enable_ai_summary': True,
            }

            # 使用CreateMeetingSerializer进行完整的时间冲突检测
            serializer = CreateMeetingSerializer(data=meeting_data)
            if serializer.is_valid():
                # 创建会议
                meeting = serializer.save(host=request.user)
                logger.info(f"会议创建成功，ID: {meeting.id}, meeting_id: {meeting.meeting_id}")

                # 立即开始会议
                meeting.status = 'active'
                meeting.actual_start_time = timezone.now()
                meeting.save()

                response_serializer = MeetingSerializer(meeting)
                return Response({
                    'success': True,
                    'meeting': response_serializer.data,
                    'message': '会议已创建并开始'
                })
            else:
                # 返回时间冲突错误，与预约会议保持一致
                logger.error(f"快速开始会议验证失败: {serializer.errors}")
                return Response({
                    'success': False,
                    'error': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            logger.error(f"快速开始会议失败: {str(e)}")
            logger.error(f"错误详情: {traceback.format_exc()}")
            return Response({
                'success': False,
                'error': f'快速开始会议失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['post'])
    def end_meeting(self, request, meeting_id=None):
        """结束会议（仅主持人）"""
        meeting = self.get_object()

        if meeting.host != request.user:
            return Response({
                'success': False,
                'error': '只有主持人可以结束会议'
            }, status=status.HTTP_403_FORBIDDEN)

        meeting.status = 'ended'
        meeting.actual_end_time = timezone.now()
        meeting.save()

        return Response({
            'success': True,
            'message': '会议已结束'
        })

    @action(detail=True, methods=['get'])
    def transcripts(self, request, meeting_id=None):
        """获取会议转写记录"""
        meeting = self.get_object()
        transcripts = meeting.transcripts.all().order_by('start_time')
        serializer = MeetingTranscriptSerializer(transcripts, many=True)

        return Response({
            'success': True,
            'transcripts': serializer.data
        })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_meeting_by_id(request, meeting_id):
    """通过会议ID获取会议信息"""
    try:
        meeting = Meeting.objects.get(meeting_id=meeting_id)

        # 检查用户是否有权限访问此会议
        if meeting.host != request.user:
            return Response({
                'success': False,
                'error': '您没有权限访问此会议'
            }, status=status.HTTP_403_FORBIDDEN)

        serializer = MeetingSerializer(meeting)
        return Response({
            'success': True,
            'meeting': serializer.data
        })

    except Meeting.DoesNotExist:
        return Response({
            'success': False,
            'error': '会议不存在'
        }, status=status.HTTP_404_NOT_FOUND)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_user_meetings(request):
    """获取用户的会议列表"""
    user = request.user

    # 处理可能被包装在params中的参数
    # 首先尝试从params对象中获取参数
    if 'params[page]' in request.GET:
        page = int(request.GET.get('params[page]', 1))
    else:
        page = int(request.GET.get('page', 1))

    if 'params[page_size]' in request.GET:
        page_size = int(request.GET.get('params[page_size]', 20))
    else:
        page_size = int(request.GET.get('page_size', 20))

    if 'params[status]' in request.GET:
        status_filter = request.GET.get('params[status]', '')
    else:
        status_filter = request.GET.get('status', '')

    if 'params[keyword]' in request.GET:
        keyword = request.GET.get('params[keyword]', '')
    else:
        keyword = request.GET.get('keyword', '')

    # 构建查询
    queryset = Meeting.objects.filter(host=user).order_by('-created_at')

    # 添加关键词搜索
    if keyword:
        queryset = queryset.filter(
            Q(title__icontains=keyword) |
            Q(meeting_id__icontains=keyword)
        )

    if status_filter:
        queryset = queryset.filter(status=status_filter)

    # 分页
    total = queryset.count()
    start = (page - 1) * page_size
    end = start + page_size
    meetings = queryset[start:end]

    # 添加调试信息
    logger.info(f"分页调试: page={page}, page_size={page_size}")
    logger.info(f"分页调试: total={total}, start={start}, end={end}")
    logger.info(f"分页调试: 实际返回数量={len(meetings)}")

    serializer = MeetingSerializer(meetings, many=True)

    return Response({
        'success': True,
        'meetings': serializer.data,
        'total': total,
        'page': page,
        'page_size': page_size
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def speech_to_text(request):
    """语音转文字接口"""
    try:
        audio_file = request.FILES.get('audio')
        if not audio_file:
            return Response({
                'success': False,
                'error': '没有提供音频文件'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 这里可以集成各种语音识别服务，比如：
        # 1. 百度语音识别 API
        # 2. 腾讯云语音识别 API
        # 3. 阿里云语音识别 API
        # 4. OpenAI Whisper API

        # 使用语音识别服务
        speech_service = get_speech_recognition_service()
        result = speech_service.recognize_audio(audio_file)

        if result.get('success'):
            return Response({
                'success': True,
                'text': result.get('text'),
                'confidence': result.get('confidence', 0.0),
                'message': '语音识别成功'
            })
        else:
            return Response({
                'success': False,
                'error': result.get('error', '语音识别失败')
            }, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        logger.error(f'语音转文字失败: {str(e)}')
        return Response({
            'success': False,
            'error': '语音识别失败'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def coze_optimize_speech(request):
    """使用Coze工作流进行语音优化"""
    try:
        audio_file = request.FILES.get('audio')
        meeting_id = request.data.get('meeting_id')

        if not audio_file:
            return Response({
                'success': False,
                'error': '没有提供音频文件'
            }, status=status.HTTP_400_BAD_REQUEST)

        if not meeting_id:
            return Response({
                'success': False,
                'error': '没有提供会议 ID'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 检查会议和用户权限
        try:
            meeting = Meeting.objects.get(meeting_id=meeting_id)
            if meeting.host != request.user:
                return Response({
                    'success': False,
                    'error': '您不在此会议中'
                }, status=status.HTTP_403_FORBIDDEN)
        except Meeting.DoesNotExist:
            return Response({
                'success': False,
                'error': '会议不存在'
            }, status=status.HTTP_404_NOT_FOUND)

        # 重置文件指针
        audio_file.seek(0)

        # 调用Coze智能体服务
        from .coze_service import get_coze_service
        coze_service = get_coze_service()
        result = coze_service.optimize_speech_text(audio_file)

        if result.get('success'):
            # 保存优化后的转写记录
            optimized_transcript = OptimizedTranscript.objects.create(
                meeting=meeting,
                speaker_name="内容",
                original_text=result.get('original_text', ''),
                optimized_text=result.get('optimized_text', ''),
                confidence=result.get('confidence', 0.0),
                start_time=timezone.now(),
                processing_time=result.get('processing_time', 0.0),
                workflow_id=getattr(settings, 'COZE_WORKFLOW_ID', ''),
                optimization_level='high'
            )

            return Response({
                'success': True,
                'original_text': result.get('original_text'),
                'optimized_text': result.get('optimized_text'),
                'confidence': result.get('confidence'),
                'processing_time': result.get('processing_time'),
                'transcript_id': optimized_transcript.id,
                'message': '语音优化成功'
            })
        else:
            # 根据错误类型返回适当的HTTP状态码
            error_message = result.get('error', 'Coze智能体处理失败')
            if '超时' in error_message:
                return Response({
                    'success': False,
                    'error': error_message
                }, status=status.HTTP_408_REQUEST_TIMEOUT)
            elif '频率超限' in error_message:
                return Response({
                    'success': False,
                    'error': error_message
                }, status=status.HTTP_429_TOO_MANY_REQUESTS)
            elif '服务暂时不可用' in error_message:
                return Response({
                    'success': False,
                    'error': error_message
                }, status=status.HTTP_503_SERVICE_UNAVAILABLE)
            else:
                return Response({
                    'success': False,
                    'error': error_message
                }, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        logger.error(f'Coze语音优化失败: {str(e)}')
        logger.error(f'错误详情: {traceback.format_exc()}')
        return Response({
            'success': False,
            'error': f'语音优化失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def generate_meeting_summary(request, meeting_id):
    """生成会议总结"""
    try:
        # 检查会议和权限
        try:
            meeting = Meeting.objects.get(meeting_id=meeting_id)
            if meeting.host != request.user:
                return Response({
                    'success': False,
                    'error': '只有主持人可以生成会议总结'
                }, status=status.HTTP_403_FORBIDDEN)
        except Meeting.DoesNotExist:
            return Response({
                'success': False,
                'error': '会议不存在'
            }, status=status.HTTP_404_NOT_FOUND)

        # 检查会议是否已结束
        if meeting.status != 'ended':
            return Response({
                'success': False,
                'error': '只有已结束的会议才能生成总结。当前会议状态为：' + dict(Meeting.STATUS_CHOICES).get(
                    meeting.status, meeting.status)
            }, status=status.HTTP_400_BAD_REQUEST)

        # 获取所有优化后的转写记录
        optimized_transcripts = meeting.optimized_transcripts.all().order_by('start_time')

        # 如果没有优化后的转写记录，尝试使用普通转写记录
        if not optimized_transcripts.exists():
            # 获取普通转写记录
            regular_transcripts = meeting.transcripts.all().order_by('start_time')
            if not regular_transcripts.exists():
                # 提供更详细的错误信息，包括会议信息
                return Response({
                    'success': False,
                    'error': f'无法生成会议总结：会议中没有语音转写内容。请确保在会议期间启用了语音转写功能并有发言内容。会议ID: {meeting_id}, 会议主题: {meeting.title}'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 将普通转写记录转换为优化后的格式
            meeting_texts = []
            for transcript in regular_transcripts:
                meeting_texts.append({
                    'timestamp': transcript.start_time.strftime('%H:%M:%S') if transcript.start_time else '',
                    'speaker': transcript.speaker_name,
                    'text': transcript.text
                })
        else:
            # 准备优化后的会议文字数据
            meeting_texts = []
            for transcript in optimized_transcripts:
                meeting_texts.append({
                    'timestamp': transcript.start_time.strftime('%H:%M:%S') if transcript.start_time else '',
                    'speaker': transcript.speaker_name,
                    'text': transcript.optimized_text or transcript.original_text
                })

        # 检查是否有会议内容
        if not meeting_texts:
            return Response({
                'success': False,
                'error': f'没有找到有效的会议记录，无法生成总结。请确保会议中有语音转写内容。会议ID: {meeting_id}, 会议主题: {meeting.title}'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 记录调试信息
        logger.info(f"准备生成会议总结，会议ID: {meeting_id}, 记录数量: {len(meeting_texts)}")
        logger.info(f"会议内容预览: {meeting_texts[:3] if len(meeting_texts) > 3 else meeting_texts}")

        # 调用Coze智能体生成总结，包含会议描述
        from .coze_service import get_coze_service
        coze_service = get_coze_service()
        summary_result = coze_service.generate_meeting_summary(meeting_texts, meeting.description)

        logger.info(f"Coze服务返回结果: {summary_result}")

        if summary_result.get('success'):
            # 保存或更新会议总结
            summary, created = MeetingSummary.objects.update_or_create(
                meeting=meeting,
                defaults={
                    'summary_text': summary_result.get('summary', ''),
                    'key_points': summary_result.get('key_points', []),
                    'action_items': summary_result.get('action_items', []),
                    'total_words': summary_result.get('word_count', 0),
                    'total_duration': (
                            meeting.actual_end_time - meeting.actual_start_time).total_seconds() if meeting.actual_end_time and meeting.actual_start_time else 0,
                    'generated_by': 'coze_agent'
                }
            )

            return Response({
                'success': True,
                'summary': summary.get_summary_data(),
                'message': '会议总结生成成功'
            })
        else:
            error_msg = summary_result.get('error', '总结生成失败')
            logger.error(f"会议总结生成失败: {error_msg}")
            # 根据错误类型返回适当的HTTP状态码
            if '超时' in error_msg:
                return Response({
                    'success': False,
                    'error': error_msg
                }, status=status.HTTP_408_REQUEST_TIMEOUT)
            elif '频率超限' in error_msg:
                return Response({
                    'success': False,
                    'error': error_msg
                }, status=status.HTTP_429_TOO_MANY_REQUESTS)
            elif '服务暂时不可用' in error_msg:
                return Response({
                    'success': False,
                    'error': error_msg
                }, status=status.HTTP_503_SERVICE_UNAVAILABLE)
            elif '没有语音转写内容' in error_msg or '没有有效的会议记录' in error_msg:
                # 提供更友好的中文提示
                return Response({
                    'success': False,
                    'error': f'无法生成会议总结：{error_msg}。请确保在会议期间启用了语音转写功能并有发言内容。'
                }, status=status.HTTP_400_BAD_REQUEST)
            else:
                return Response({
                    'success': False,
                    'error': error_msg
                }, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        logger.error(f'生成会议总结失败: {str(e)}')
        logger.error(f'错误详情: {traceback.format_exc()}')
        return Response({
            'success': False,
            'error': f'生成总结失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_meeting_summary(request, meeting_id):
    """获取会议总结"""
    try:
        meeting = Meeting.objects.get(meeting_id=meeting_id)

        # 检查用户权限
        if meeting.host != request.user:
            return Response({
                'success': False,
                'error': '您没有权限访问此会议总结'
            }, status=status.HTTP_403_FORBIDDEN)

        try:
            summary = meeting.summary
            return Response({
                'success': True,
                'summary': summary.get_summary_data()
            })
        except MeetingSummary.DoesNotExist:
            return Response({
                'success': False,
                'error': '该会议尚未生成总结'
            }, status=status.HTTP_404_NOT_FOUND)

    except Meeting.DoesNotExist:
        return Response({
            'success': False,
            'error': '会议不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.error(f'获取会议总结失败: {str(e)}')
        return Response({
            'success': False,
            'error': '获取总结失败'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def download_meeting_summary(request, meeting_id):
    """下载会议总结"""
    try:
        from django.http import HttpResponse
        import re

        meeting = Meeting.objects.get(meeting_id=meeting_id)

        # 检查用户权限
        if meeting.host != request.user:
            return Response({
                'success': False,
                'error': '您没有权限下载此会议总结'
            }, status=status.HTTP_403_FORBIDDEN)

        try:
            summary = meeting.summary
        except MeetingSummary.DoesNotExist:
            return Response({
                'success': False,
                'error': '该会议尚未生成总结'
            }, status=status.HTTP_404_NOT_FOUND)
            # 获取请求的文件格式参数
        file_format = request.GET.get('format', 'txt')  # 默认为txt格式

        # 限制只支持txt和docx格式，移除md格式
        if file_format not in ['txt', 'docx']:
            file_format = 'txt'  # 默认为txt格式

        # 创建文本格式的总结，与前端显示格式保持一致
        # 处理summary_text可能包含JSON的情况
        import json
        try:
            # 尝试解析summary_text为JSON
            summary_data = json.loads(summary.summary_text)
            # 如果是JSON格式且包含message字段，则使用该消息
            if 'message' in summary_data:
                summary_content = summary_data['message']
            else:
                summary_content = summary.summary_text
        except json.JSONDecodeError:
            # 如果不是JSON格式，直接使用原文本
            summary_content = summary.summary_text

        # 清理Markdown标记，确保下载的内容没有##号等标记
        def clean_markdown(text):
            if not text:
                return ""
            # 移除Markdown标题标记（包括多级标题）
            text = re.sub(r'^#{1,6}\s*', '', text, flags=re.MULTILINE)
            # 移除粗体标记
            text = re.sub(r'\*\*(.*?)\*\*', r'\1', text)
            # 移除斜体标记
            text = re.sub(r'\*(.*?)\*', r'\1', text)
            # 移除多余的星号
            text = re.sub(r'\*+', '', text)
            # 移除行内代码标记
            text = re.sub(r'`+', '', text)
            # 移除引用标记
            text = re.sub(r'^>\s*', '', text, flags=re.MULTILINE)
            # 移除分隔线
            text = re.sub(r'^[-*]{3,}\s*$', '', text, flags=re.MULTILINE)
            return text.strip()

        # 清理总结内容
        clean_summary_content = clean_markdown(summary_content)

        # 准备基础内容
        basic_content = f"""会议总结

会议信息：
会议主题：{meeting.title}
会议描述：{meeting.description if meeting.description else '暂无'}
会议时间：{meeting.actual_start_time.strftime('%Y-%m-%d %H:%M:%S') if meeting.actual_start_time else '未开始'}
会议时长：{summary.total_duration}秒

总结内容
{clean_summary_content}

关键要点："""

        # 添加关键要点，使用列表格式，并清理Markdown标记
        for point in summary.key_points:
            clean_point = clean_markdown(point) if isinstance(point, str) else point
            basic_content += f"\n• {clean_point}"

        # 添加签名
        basic_content += "\n\n签名："

        # 只支持txt和docx格式，移除md格式
        if file_format == 'docx':
            # Word格式处理
            try:
                from docx import Document
                from io import BytesIO

                document = Document()
                document.add_heading('会议总结', 0)

                # 添加内容到Word文档
                lines = basic_content.split('\n')
                for line in lines:
                    if line.strip():
                        if line.startswith('会议信息：') or line.startswith('总结内容') or line.startswith(
                                '关键要点：') or line.startswith('签名：'):
                            document.add_heading(line.strip(), level=1)
                        elif line.startswith('会议主题：') or line.startswith('会议描述：') or line.startswith(
                                '会议时间：') or line.startswith('会议时长：'):
                            document.add_paragraph(line.strip(), style='Intense Quote')
                        elif line.startswith('•'):
                            document.add_paragraph(line.strip(), style='List Bullet')
                        else:
                            document.add_paragraph(line.strip())

                buffer = BytesIO()
                document.save(buffer)
                docx_data = buffer.getvalue()
                buffer.close()

                response = HttpResponse(docx_data,
                                        content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                response[
                    'Content-Disposition'] = f'attachment; filename="{meeting.title}_总结_{timezone.now().strftime("%Y%m%d")}.docx"'
                return response

            except ImportError:
                # 如果没有安装python-docx，则返回txt格式
                response = HttpResponse(basic_content.encode('utf-8'), content_type='text/plain; charset=utf-8')
                response[
                    'Content-Disposition'] = f'attachment; filename="{meeting.title}_总结_{timezone.now().strftime("%Y%m%d")}.txt"'
                return response

        else:
            # 默认返回文本格式
            content = basic_content

        # 根据格式返回相应的内容
        response = HttpResponse(content.encode('utf-8'), content_type='text/plain; charset=utf-8')
        response[
            'Content-Disposition'] = f'attachment; filename="{meeting.title}_总结_{timezone.now().strftime("%Y%m%d")}.txt"'
        return response

    except Meeting.DoesNotExist:
        return Response({
            'success': False,
            'error': '会议不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        logger.error(f'下载会议总结失败: {str(e)}')
        return Response({
            'success': False,
            'error': '下载失败'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def save_transcript(request):
    """保存会议转写记录"""
    data = request.data

    try:
        # 使用meeting_id而不是id来查找会议
        meeting = Meeting.objects.get(meeting_id=data.get('meeting_id'))

        # 检查用户是否是会议主持人
        if meeting.host != request.user:
            return Response({
                'success': False,
                'error': '您不是此会议的主持人'
            }, status=status.HTTP_403_FORBIDDEN)

        transcript = MeetingTranscript.objects.create(
            meeting=meeting,
            speaker_name=request.user.username,
            text=data.get('text'),
            confidence=data.get('confidence', 0.0),
            start_time=timezone.now(),
            end_time=timezone.now(),
            duration=data.get('duration', 0)
        )

        serializer = MeetingTranscriptSerializer(transcript)
        return Response({
            'success': True,
            'transcript': serializer.data
        })

    except Meeting.DoesNotExist:
        return Response({
            'success': False,
            'error': '会议不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        logger.error(f'保存转写记录失败: {str(e)}')
        logger.error(f'错误详情: {traceback.format_exc()}')
        return Response({
            'success': False,
            'error': '保存失败'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
